from flask import session, current_app, render_template, jsonify, request, g

from info import redis_store, constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_bp

"""views中就导入蓝图对象就可以使用蓝图完成视图函数了"""


@index_bp.route('/favicon.ico')
def get_favicon():

    # redis_store.set("name", "laowang")

    # session["name"] = "hehe"

    """发送静态文件到浏览器的方法"""
    return current_app.send_static_file("news/favicon.ico")


@index_bp.route('/')
@user_login_data
def index():

    # user_id = session.get("user_id")
    #
    # user = None
    #
    # if user_id:
    #
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")

    user = g.user

    # 查询新闻点击数据
    try:
        news_clicks_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询异常")

    news_rank_dict = []

    for news_obj in news_clicks_list if news_clicks_list else []:

        news_obj_dict = news_obj.to_dict()

        news_rank_dict.append(news_obj_dict)

    # 查询分类列表
    try:
        categoris_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询分类列表异常")

    # 分类列表对象转换成字典列表
    categoris_list_dict = []
    for categories in categoris_list if categoris_list else []:
        categories_dict = categories.to_dict()
        categoris_list_dict.append(categories_dict)

    # to_dict: 将用户对象转化成字典
    data = {
        "user_info": user.to_dict() if user else None,
        "news_rank_list": news_rank_dict,
        "categoris_list_dict":categoris_list_dict
    }

    return render_template("news/index.html", data=data)


@index_bp.route('/news_list')
def news_list():

    # 获取参数
    param_dict = request.args
    cid = param_dict.get("cid")
    page = param_dict.get("page", 1)
    per_page = param_dict.get("per_page", constants.HOME_PAGE_MAX_NEWS)

    # 参数校验
    if not cid:
        current_app.logger.error("参数不足")
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数格式异常")

    # if cid != 1:
    #
    #     paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc())\
    #             .paginate(page, per_page, False)
    # else:
    #     paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page, per_page, False)

    # 逻辑处理
    filter_list = []

    if cid != 1:
        filter_list.append(News.category_id == cid)

    try:
        paginate = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(page, per_page
                                                                                              , False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象异常")

    news_list_dict = []
    for news in news_list if news_list else []:
        news_obj = news.to_dict()
        news_list_dict.append(news_obj)

    data = {
        "cid": cid,
        "newsList": news_list_dict,
        "current_page": current_page,
        "total_page": total_page
    }

    # 返回值
    return jsonify(errno=RET.OK,errmsg="OK", data=data)
